import argparse
import sys
import logging
from .core import FaceRecognition
from .utils import setup_logging

def main():
    """命令行工具主函数"""
    parser = argparse.ArgumentParser(description='人脸识别系统命令行工具')
    parser.add_argument('command', choices=['add', 'list', 'remove', 'test'],
                      help='要执行的命令: add(添加人脸), list(列出所有人), remove(删除人脸), test(测试识别)')
    parser.add_argument('--name', help='人员姓名')
    parser.add_argument('--timeout', type=int, default=3, help='识别超时时间(秒)')
    parser.add_argument('--debug', action='store_true', help='启用调试模式')
    
    args = parser.parse_args()
    
    # 设置日志级别
    setup_logging(level=logging.DEBUG if args.debug else logging.INFO)
    
    try:
        # 初始化人脸识别模块
        recognizer = FaceRecognition()
        
        if args.command == 'add':
            if not args.name:
                print("错误: 添加人脸需要指定 --name 参数")
                sys.exit(1)
            success, message = recognizer.add_person(args.name)
            print(message)
            sys.exit(0 if success else 1)
            
        elif args.command == 'list':
            persons = recognizer.database.get_all_persons()
            if not persons:
                print("数据库中还没有人脸记录")
            else:
                print("\n当前数据库中的人员:")
                for person in persons:
                    print(f"姓名: {person['name']}")
                    print(f"创建时间: {person['created_at']}")
                    print(f"更新时间: {person['updated_at']}")
                    print(f"人脸图像数量: {len(person['face_images'])}")
                    print("-" * 30)
            sys.exit(0)
            
        elif args.command == 'remove':
            if not args.name:
                print("错误: 删除人脸需要指定 --name 参数")
                sys.exit(1)
            success, message = recognizer.database.remove_person(args.name)
            print(message)
            if success:
                # 重新训练识别器
                recognizer.train_recognizer()
            sys.exit(0 if success else 1)
            
        elif args.command == 'test':
            print(f"正在测试人脸识别，超时时间: {args.timeout}秒")
            print("请面对摄像头，按q键退出")
            
            result = recognizer.recognize_with_timeout(args.timeout)
            if result:
                print(f"\n识别结果:")
                print(f"姓名: {result['person_name']}")
                print(f"置信度: {result['confidence']:.2f}%")
            else:
                print("\n未能识别到人脸")
            sys.exit(0)
            
    except KeyboardInterrupt:
        print("\n操作被用户中断")
        sys.exit(1)
    except Exception as e:
        logging.error(f"发生错误: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main() 